package com.mall507.fivepeaks.activity.mine;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hzh.frame.comn.annotation.SelectTable;
import com.hzh.frame.comn.annotation.ViewInject;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.ui.activity.BaseUI;
import com.hzh.frame.util.AndroidUtil;
import com.hzh.frame.util.FileUtil;
import com.hzh.frame.util.StatusBarUtil;
import com.hzh.frame.widget.xdialog.XDialogSubmit;
import com.mall507.comn.matisse.GifSizeFilter;
import com.mall507.comn.model.User;
import com.mall507.comn.tools.UserTools;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.widget.imageview.CircleImageView;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 设置头像
 */
@Route(path = "/mine/MineHeadUI")
public class MineHeadUI extends BaseUI {

    private static final int REQUEST_IMAGE = 1;// 图片选择
    private static final int REQUEST_CROP = 2;// 图片剪裁
    @ViewInject(R.id.head)
    CircleImageView head;//头像
    private File headFile;//头像

    @Override
    protected void onCreateBase() {
        setContentView(R.layout.ui_user_core_head);
        getTitleView().setContent("头像");
        head.setImageURI(UserTools.getInstance().getUser().getHead());
    }

    /**
     * 相机
     */
    public void openCamera(View view) {
        Matisse.from(this).choose(MimeType.ofImage()).theme(R.style.Matisse_Dracula)
                //                .countable(true)//有序选择图片 123456...
                .maxSelectable(1)//最大选择数量为1
                .countable(false).capture(true)//拍照
                .captureStrategy(new CaptureStrategy(true, AndroidUtil.getPackageName() + ".fileProvider"))//拍照
                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K)).maxSelectable(9).originalEnable(true).maxOriginalSize(10).imageEngine(new PicassoEngine()).forResult(REQUEST_IMAGE);
    }

    /**
     * 相册
     */
    public void openPhoto(View view) {
        Matisse.from(this).choose(MimeType.ofImage()).theme(R.style.Matisse_Dracula).maxSelectable(1)//最大选择数量为1
                .countable(false).addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K)).maxSelectable(9).originalEnable(true).maxOriginalSize(10).imageEngine(new PicassoEngine()).forResult(REQUEST_IMAGE);
    }

    /**
     * 启动裁剪
     *
     * @param activity  上下文
     * @param sourceUir 需要裁剪图片的Uri
     * @return
     */
    public void startUCrop(Activity activity, Uri sourceUir) {
        //裁剪后保存到文件中
        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), System.currentTimeMillis() + ".jpg"));
        //初始化，第一个参数：需要裁剪的图片；第二个参数：裁剪后图片
        UCrop uCrop = UCrop.of(sourceUir, destinationUri);
        UCrop.Options options = new UCrop.Options();//初始化UCrop配置
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);//设置剪裁出来的是JPEG格式的图片
        options.setCircleDimmedLayer(true);//设置是否展示圆形剪裁框
        options.setShowCropFrame(false);//设置是否展示矩形剪裁框
        options.setShowCropGrid(false);//设置是否展示网格剪裁框
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);//设置裁剪图片可操作的手势 缩放、旋转、剪裁,none就是不设置
        //        options.setToolbarColor(ActivityCompat.getColor(activity, R.color.dracula_primary));//设置toolbar颜色
        options.setStatusBarColor(ActivityCompat.getColor(activity, R.color.black_bg));//设置状态栏颜色
        //        options.setHideBottomControls(true);//是否隐藏底部容器，默认显示
        options.setFreeStyleCropEnabled(false);//是否能调整裁剪图片的宽高比
        uCrop.withOptions(options);
        uCrop.withAspectRatio(1, 1);//设置裁剪图片的宽高比，比如16：9（设置后就不能选择其他比例了、选择面板就不会出现了）
        uCrop.start(activity, REQUEST_CROP);
        StatusBarUtil.setBlackIcon(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        StatusBarUtil.setWhileIcon(this);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE:// 图片选择
                    if (resultCode == -1) {//-1:确定 0:取消
                        List<Uri> imageUris = Matisse.obtainResult(data);
                        if (imageUris != null && imageUris.size() > 0) {
                            startUCrop(this, imageUris.get(0));
                        }
                    }
                    break;
                case REQUEST_CROP:// 裁剪图片
                    headFile = new File(FileUtil.getFilePathFromContentUri(this, UCrop.getOutput(data)));
                    head.setImageURI(Uri.fromFile(headFile));
                    send();
                    break;
            }
        }
    }

    public void send() {
        List<HashMap<String, Object>> fileList = new ArrayList<>();
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("name", "head");
        map1.put("file", headFile);
        fileList.add(map1);
        BaseHttp.getInstance().uploadFile("upload/image", fileList, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (response.optInt("code") == 200) {
                    JSONArray array = response.optJSONArray("url");
                    if (array != null && array.length() > 0) {
                        JSONObject object = array.optJSONObject(0);
                        submit(object.optString("val"));
                    }
                } else {
                    alert(response.optString("msg"));
                }
            }
        }.setSubmit(new XDialogSubmit(this).setMsg("上传中").alert()));
    }

    protected void submit(String path) {
        JSONObject params = new JSONObject();
        try {
            params.put("type", 1);
            params.put("head_img", path);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BaseHttp.getInstance().write("Me/Edit", params, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (response.optInt("code") == 200) {
                    User user = UserTools.getInstance().getUser().setHead(response.optString("data"));
                    UserTools.getInstance().updUser(user);
                    head.setImageURI(user.getHead());//显示图片
                }
                alert(response.optString("msg"));
            }
        });
    }

}
